const co = require('co');
const moment = require("moment");
const uuid = require('uuid');
const security = require('../providers/security');

const E_LINK_APP_ID = '1069695975';
const E_LINK_APP_SECRET = '686b0766c1174583e82b2c3c6bcdade7';

var httpRequest = function (opt,httpOnly) {
    return function (callback) {
		opt.headers = opt.headers || {};
		opt.headers["accept-encoding"] = "gzip,deflate";

        console.log(opt.headers);

		var http = httpOnly ? require('http') : require('https');
        var req = http.request(opt,function(res){
            var resChunks = [];
            res.on('data', function (chunk) {
                resChunks.push(chunk);
            });
            res.on('end',function () {
                var buffer = Buffer.concat(resChunks);
                  var encoding = res.headers['content-encoding'];
                  if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function(err, decoded) {
                      callback(err, decoded && decoded.toString());
                    });
                  } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function(err, decoded) {
                      callback(err, decoded && decoded.toString());
				  	});
                  } else {
                    callback(null, buffer.toString());
                  }
            });
        });
        req.on('error',function(err){
			console.log('request.error:' + err.message);
            callback(err,null);
        });
		if (opt.data){
            console.log(opt.data);
			req.write(opt.data);
		}
        req.end();
    }
}

var getAccessToken = function*() {
    const ts = moment().unix();
    const sign = security.md5(E_LINK_APP_ID + ts + E_LINK_APP_SECRET);

    var data = "client_id=" + E_LINK_APP_ID;
    data += "&grant_type=client_credentials";
    data += "&sign=" + sign;
    data += "&scope=all";
    data += "&timestamp=" + ts;
    data += "&id=" + uuid.v4();

    console.log(data);

    var opt = {
        host: "open-api.10ss.net",
        path: "/oauth/oauth",
        method: "POST",
        data: data,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": data.length
        }
    };
    const res = yield httpRequest(opt, false);
    console.log(res);
}

var print = function *(accessToken,content) {
    const ts = moment().unix();
    const sign = security.md5(E_LINK_APP_ID + ts + E_LINK_APP_SECRET);
    var data = "client_id=" + E_LINK_APP_ID;
    data += "&access_token=" + accessToken;
    data += "&machine_code=4004542167";
    data += "&sign=" + sign;
    data += "&timestamp=" + ts;
    data += "&id=" + uuid.v4();
    data += "&origin_id=" + uuid.v4().replace(/-/g,'');
    data += "&content=" + encodeURIComponent(content);

    var opt = {
        host: "open-api.10ss.net",
        path: "/print/index",
        method: "POST",
        data: data,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": data.length
        }
    };
    const res = yield httpRequest(opt, false);
    console.log(res);
}

var getInfo = function *(accessToken) {
    const ts = moment().unix();
    const sign = security.md5(E_LINK_APP_ID + ts + E_LINK_APP_SECRET);
    var data = "client_id=" + E_LINK_APP_ID;
    data += "&access_token=" + accessToken;
    data += "&machine_code=4004542167";
    data += "&sign=" + sign;
    data += "&timestamp=" + ts;
    data += "&id=" + uuid.v4();

    var opt = {
        host: "open-api.10ss.net",
        path: "/printer/printinfo",
        method: "POST",
        data: data,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": data.length
        }
    };
    const res = yield httpRequest(opt, false);
    console.log(res);
}

co(function *() {
    var accessToken = yield getAccessToken();
    // var accessToken = 'e4a071a24e55432ab05b88405f93f452';
    //
    // var content = "<FB><center>弘道智能餐厅</center></FB>";
    // content += "<center>************</center>";
    // content += "机号:001 流水:4004542167\n";
    // content += "2017-09-07 00:34:12\n";
    //
    // content += "--------------------------------\n";
    // content += "<table>";
    // content += "<tr><td>菜品</td><td>数量</td><td>单价</td><td>金额</td></tr>";
    // content += "<tr><td>红烧肉</td><td>1</td><td>20.00</td><td>20.00</td></tr>";
    // content += "<tr><td>梅菜扣肉</td><td>1</td><td>32.00</td><td>32.00</td></tr>";
    // content +="</table>";
    // content += "--------------------------------";
    // content += "<FB><right>总计：52.00</right></FB>";
    //
    // //yield getInfo(accessToken);
    // yield print(accessToken,content);
})
